package com.shangcheng.goods.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shangcheng.goods.dao.SkuMapper;
import com.shangcheng.goods.pojo.Sku;
import com.shangcheng.goods.service.SkuService;
import com.shangcheng.orders.dao.OrderItemMapper;
import com.shangcheng.orders.pojo.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SkuServiceImpl implements SkuService {
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public Map search(Map<String, String> searchMap) {
        String keyword = searchMap.get("keywords");
        if (keyword.contains("")) {
            List<Sku> skuList = skuMapper.searchByName("%" + keyword + "%");
            Map resultMap = new HashMap();
            resultMap.put("rows", skuList);
            return resultMap;
        } else {
            return null;
        }
    }

    @Override
    public List<Sku> findList(Sku sku) {
        return skuMapper.select(sku);
    }



    @Override
    public Sku findById(Long id) {
        return skuMapper.selectByPrimaryKey(id);
    }

    /**
     * 扣减库存
     *
     * @param username
     */
    @Override
    public void decrCount(String username) {
        // 获取购物车数据
        List<OrderItem> orderItems = orderItemMapper.selectByName(username);
        if (orderItems != null && orderItems.size() > 0) {
            for (OrderItem orderItem : orderItems) {
                // 扣减库存,更新库存表
                // update tb_sku set num = num - 20 where id = skuId and num > 20  // 防止超卖
                int count = skuMapper.decrCount(orderItem.getSkuId(), orderItem.getNum());
                if (count <= 0) {
                    throw new RuntimeException("商品库存不足，请减少购买数量！！！");
                }
            }
        }
    }
}